
<?php

$g_session_dbconn;
$g_session_redis;
$g_login_dbconn;

function dal_session_get_dbconn()
{
	global $g_session_dbconn;
	
	if (isset($g_session_dbconn))
		return $g_session_dbconn;
	
	$g_session_dbconn = dal_getconn($GLOBALS['g_dal_session_dbstr']);
	return $g_session_dbconn;
}

function dal_session_get_redis()
{
	global $g_session_redis;
	
	if (isset($g_session_redis))
		return $g_session_redis;
	
	$g_session_redis = dal_getconn($GLOBALS['g_dal_session_redis']);
	return $g_session_redis;
}

function dal_login_get_dbconn()
{
	global $g_login_dbconn;
	
	if (isset($g_login_dbconn))
		return $g_login_dbconn;
	
	$g_login_dbconn = dal_getconn($GLOBALS['g_dal_login_dbstr']);
	return $g_login_dbconn;
}

function dal_session_add($token, $time, $user_id, $device_id, $app, $os, $ip)
{
	global $g_dal_login_history_daily;
	
	if ($GLOBALS['g_dal_session_redis_enable']) {
		$t_conn = dal_session_get_redis();
		$t_conn->set('session-' . $token, $time, $user_id);
	} else {
		$t_conn   = dal_session_get_dbconn();
		$t_sql    = "INSERT INTO mocool_session_table values('$token', NOW()+$time, $user_id, '$device_id', '$app', '$os', '$ip')";
		$t_result = mysql_query($t_sql, $t_conn);
		if (!$t_result) {
			dal_mysql_error($t_conn, $t_sql, __FUNCTION__);
			return false;
		}
	}
	
	if ($g_dal_login_history_daily) {
		$t_prefix = '_' . date('Ymd');
	} else {
		$t_prefix = '';
	}
	$t_conn   = dal_login_get_dbconn();
	$t_sql    = "INSERT INTO mocool_login_history_table$t_prefix(user_id, device_id, app, os, ip) VALUES($user_id, '$device_id','$app', '$os', '$ip')";
	$t_result = mysql_query($t_sql, $t_conn);
	if (!$t_result) {
		dal_mysql_error($t_conn, $t_sql, __FUNCTION__);
	}
	
	return true;
}

function dal_session_get($token)
{
	if ($GLOBALS['g_dal_session_redis_enable']) {
		$t_conn  = dal_session_get_redis();
		$user_id = $t_conn->get('session-' . $token);
		if (!$user_id)
			return false;
		return $user_id;
	} else {
		$t_conn   = dal_session_get_dbconn();
		$t_sql    = "SELECT user_id FROM mocool_session_table WHERE token='$token'";
		$t_result = mysql_query($t_sql, $t_conn);
		if (!$t_result) {
			dal_mysql_error($t_conn, $t_sql, __FUNCTION__);
			return -1;
		}
		if (mysql_num_rows($t_result) != 1) {
			return -1;
		}
		$t_row = mysql_fetch_array($t_result);
		return $t_row['user_id'];
	}
}

function dal_session_del($token)
{
	if ($GLOBALS['g_dal_session_redis_enable']) {
		$t_conn = dal_session_get_redis();
		$t_conn->delete('session-' . $token);
	} else {
		$t_conn = dal_session_get_dbconn();
		$t_sql  = "DELETE FROM mocool_session_table WHERE token='$token'";
		mysql_query($t_sql, $t_conn);
	}
}

?>
